package com.tvunetworks.center.device.service.impl;

import com.tvunetworks.center.device.constant.DeviceConstant;
import com.tvunetworks.center.device.mapper.CustomizedShareRecordMapper;
import com.tvunetworks.center.device.model.CustomizedShareRecord;
import com.tvunetworks.center.device.service.CustomizedShareRecordService;
import com.tvunetworks.center.device.service.CustomizedTShareAccountService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @program: tvucc-aggregator
 * @description: CustomizedShareRecordServiceImpl
 * @author lebronchen
 * @create: 2020-03-13 09:52
 **/
@Service
@Slf4j
public class CustomizedShareRecordServiceImpl extends BaseService<CustomizedShareRecord> implements CustomizedShareRecordService {

    @Autowired
    private CustomizedShareRecordMapper customizedShareRecordMapper;
    @Autowired
    private CustomizedTShareAccountService customizedTShareAccountService;

    @Override
    @Transactional
    public void startStopShareAddShareRecord(String userId, String sid, String shareId, boolean shareShare) {
        this.addShareRecord(userId, sid, shareId, shareShare, false);
    }

    @Override
    @Transactional
    public void stopLiveAddShareRecord(String userId, String sid, String shareId) {
        this.addShareRecord(userId, sid, shareId, false, true);
    }

    @Override
    public Set<String> clearAndListStartLiveNeedAutoShareIds(String userId, String sid) {
        if (StringUtils.isEmpty(userId) || StringUtils.isEmpty(sid)) {
            log.error("clearAndListStartLiveNeedAutoShareIds param error userId:{} sid:{}", userId, sid);
            return null;
        }
        CustomizedShareRecord record = new CustomizedShareRecord()
                .setSid(sid)
                .setStatus(DeviceConstant.ShareRecord.NEED_SHARE);
        List<CustomizedShareRecord> list = super.selectExistList(record);
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }

        Set<String> shareIds = new HashSet<>();
        for (CustomizedShareRecord shareRecord : list) {
            if (StringUtils.equals(userId, shareRecord.getUserId())) {
                // 推流记录属于当前用户的，记录下来需要自动推流，并且清除
                shareIds.add(shareRecord.getShareId());
                shareRecord.setStatus(DeviceConstant.ShareRecord.NEED_SHARE_DONE);
            } else {
                // 推流记录不属于当前用户的，不需要记录，并且清除标记为失败状态
                shareRecord.setStatus(DeviceConstant.ShareRecord.NEED_SHARE_FAILED_NOT_BELONG_USER);
            }
            super.update(shareRecord);
        }
        log.error("StartLive clearAndListStartLiveNeedAutoShareIds sid:{} shareIds:{}", sid, shareIds);
        return shareIds;
    }


    /**
     * @param sid
     * @param shareId
     * @param startShare          开启/关闭  推流
     * @param stopLive       是否是关闭直播导致推流结束，下次开启直播还需要继续推流
     */
    private void addShareRecord(String userId, String sid, String shareId, boolean startShare, boolean stopLive) {

        if (StringUtils.isEmpty(sid) || StringUtils.isEmpty(shareId)) {
            log.error("startStopShareAddShareRecord issue param error sid:{} nickName:{}", sid, shareId);
            return;
        }

        // 是否是固定地址的推流，是的话，只做记录，后续不处理
        boolean fixedAddress = customizedTShareAccountService.isFixedShareAccount(shareId);

        int checkStatus;
        if (fixedAddress) {
            checkStatus = DeviceConstant.ShareRecord.FIXED_ADDRESS_START;
        } else {
            checkStatus = DeviceConstant.ShareRecord.START;
        }
        // 根据时间倒叙查出这个 Source 和这个 shareAccount 所有的正在推流的记录
        List<CustomizedShareRecord> sharingList = customizedShareRecordMapper.listSourceShareRecord(sid, shareId, checkStatus);
        if (startShare) {
            // 开始推流记录
            // 1.查询这个 Source 和这个 shareAccount 是否存在正在 share 的，存在的话，先置为结束
            if (!CollectionUtils.isEmpty(sharingList)) {
                for (CustomizedShareRecord shareRecord : sharingList) {
                    if (fixedAddress) {
                        log.error("startStopShareAddShareRecord fixedAddress issue add start exist sharingList sid:{} shareId:{} sharingList:{}", sid, shareId, sharingList);
                        shareRecord.setStatus(DeviceConstant.ShareRecord.FIXED_ADDRESS_ISSUE)
                                .setMsg("When add fixedAddress start share record, stop the existed start share record");
                        super.update(shareRecord);
                    } else {
                        log.error("startStopShareAddShareRecord issue add start exist sharingList sid:{} shareId:{} sharingList:{}", sid, shareId, sharingList);
                        shareRecord.setStatus(DeviceConstant.ShareRecord.ISSUE)
                                .setMsg("When add start share record, stop the existed start share record");
                        super.update(shareRecord);
                    }

                }
            }
            int insertStatus;
            if (fixedAddress) {
                insertStatus = DeviceConstant.ShareRecord.FIXED_ADDRESS_START;
            } else {
                insertStatus = DeviceConstant.ShareRecord.START;
            }
            // 2.添加推流记录
            CustomizedShareRecord record = new CustomizedShareRecord()
                    .setUserId(userId)
                    .setSid(sid)
                    .setShareId(shareId)
                    .setStatus(insertStatus);
            super.insert(record);
            if (fixedAddress) {
                log.error("startStopShareAddShareRecord fixedAddress normal add start record sid:{} shareId:{}", sid, shareId);
            } else {
                log.error("startStopShareAddShareRecord normal add start record sid:{} shareId:{}", sid, shareId);
            }
        } else {
            // 结束推流记录
            if (CollectionUtils.isEmpty(sharingList)) {
                // 不存在正在推流的记录
                int insertStatus;
                String msg;
                if (fixedAddress) {
                    // 添加提条 fixed_address_stop 的记录
                    insertStatus = DeviceConstant.ShareRecord.FIXED_ADDRESS_STOP;
                    msg = "Not exist starting record, add fixed_address_stop record";
                } else {
                    if (stopLive) {
                        // 添加一条 stop 的记录
                        insertStatus = DeviceConstant.ShareRecord.NEED_SHARE;
                        msg = "Not exist starting record, add need share record";
                    } else {
                        // 添加一条 stop 的记录
                        insertStatus = DeviceConstant.ShareRecord.STOP;
                        msg = "Not exist starting record, add stop record";
                    }
                }

                CustomizedShareRecord record = new CustomizedShareRecord()
                        .setUserId(userId)
                        .setSid(sid)
                        .setShareId(shareId)
                        .setStatus(insertStatus)
                        .setMsg(msg);
                super.insert(record);
                if (fixedAddress) {
                    log.error("startStopShareAddShareRecord fixedAddress issue add stop not exist sharingList, insertion fixed_address_stop record sid:{} shareId:{}", sid, shareId);
                } else {
                    log.error("startStopShareAddShareRecord issue add stop not exist sharingList, insertion stop record sid:{} shareId:{}", sid, shareId);
                }
            } else {
                // 存在正在推流的记录
                // 把最近的一条记录修改为 need_share
                CustomizedShareRecord record = sharingList.get(0);
                int updateStatus;
                if (fixedAddress) {
                    updateStatus = DeviceConstant.ShareRecord.FIXED_ADDRESS_STOP;
                } else {
                    if (stopLive) {
                        updateStatus = DeviceConstant.ShareRecord.NEED_SHARE;
                    } else {
                        updateStatus = DeviceConstant.ShareRecord.STOP;
                    }
                }
                record.setStatus(updateStatus);
                super.update(record);
                if (fixedAddress) {
                    log.error("startStopShareAddShareRecord fixedAddress normal stop share record sid:{} shareId:{}", sid, shareId);
                } else {
                    log.error("startStopShareAddShareRecord normal stop share record sid:{} shareId:{}", sid, shareId);
                }
                // 如果还存在别的推流记录，在这里清除掉
                if (sharingList.size() > 1) {
                    int exUpdateStatus;
                    String exMsg;
                    if (fixedAddress) {
                        exUpdateStatus = DeviceConstant.ShareRecord.FIXED_ADDRESS_ISSUE;
                        exMsg = "When add stop fixedAddress share record, more than one sharing record, stop the redundant start share record";
                    } else {
                        exUpdateStatus = DeviceConstant.ShareRecord.ISSUE;
                        exMsg = "When add stop share record, more than one sharing record, stop the redundant start share record";
                    }
                    log.error("startStopShareAddShareRecord issue add stop exist {} sharingList sid:{} shareId:{} sharingList:{}", sid, shareId, sharingList.size(), sharingList);
                    for (int i = 1; i < sharingList.size(); i++) {
                        CustomizedShareRecord shareRecord = sharingList.get(i);
                        shareRecord.setStatus(exUpdateStatus)
                                .setMsg(exMsg);
                        super.update(shareRecord);
                    }
                }
            }
        }
    }

}
